package com.dxy.auth.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.dxy.auth.provider.UserServiceProvider;
import com.dxy.auth.service.AuthService;
import com.dxy.common.user.AuthUserSubject;
import com.dxy.common.exp.ServiceException;
import com.dxy.common.pojo.Group;
import com.dxy.common.pojo.Resource;
import com.dxy.common.pojo.Role;
import com.dxy.common.pojo.User;
import com.dxy.common.utils.JwtUtil;
import com.dxy.common.utils.MD5Util;
import com.dxy.common.vo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;

import java.util.List;

@Slf4j
@Service
public class AuthServiceImpl implements AuthService {

    private PathMatcher pathMatcher = new AntPathMatcher();

    @Autowired
    private UserServiceProvider userServiceProvider;

    @Override
    public String login(String username, String password) {
        Result<User> result = userServiceProvider.findUserByUserName(username);
        User user = result.getData();
        if (user == null) {
            throw new ServiceException("用户不存在！");
        }
        if (user.getStatus() != 0) {
            throw new ServiceException("用户被禁用！");
        }
        if (!MD5Util.getEncryptPassword(password).equals(user.getPassword())) {
            throw new ServiceException("密码错误！");
        }

        // 查询组织、角色
        Result<List<Group>> groupResult = userServiceProvider.findUserGroup(user.getUid());
        Result<List<Role>> roleResult = userServiceProvider.findUserRole(user.getUid());
        AuthUserSubject authUserSubject = new AuthUserSubject(user, groupResult.getData(), roleResult.getData());
        return JwtUtil.createToken(user.getUid() + "", authUserSubject);
    }

    @Override
    public boolean checkPermission(Integer userId, String url) {
        Result<List<Resource>> resourceResult = userServiceProvider.findUserResource(userId);
        List<Resource> resourceList = resourceResult.getData();
        if (CollUtil.isEmpty(resourceList)) {
            return false;
        }

        for (Resource resource : resourceList) {
            if (pathMatcher.match(resource.getUrl(), url)) {
                return true;
            }
        }

        return false;
    }
}
